<template>
  <div class="container">
    <h1 class="title">欢迎使用基金研究系统</h1>
    <h2 class="subtitle">市场公募基金查询</h2>

    <!-- 筛选区域 -->
    <el-row class="filters" gutter="12" align="middle">
      <el-col :xs="24" :sm="8">
        <el-select
            v-model="selectedTags"
            multiple
            collapse-tags
            collapse-tags-tooltip
            placeholder="选择标签"
            @change="fetchFunds"
            clearable
            style="width: 100%;"
        >
          <el-option v-for="tag in tags" :key="tag.id" :label="tag.name" :value="tag.name" />
        </el-select>
      </el-col>

      <el-col :xs="24" :sm="8">
        <el-input
            v-model="keyword"
            placeholder="输入基金名称或代码"
            prefix-icon="el-icon-search"
            clearable
            style="width: 100%;"
        />
      </el-col>

      <el-col :xs="12" :sm="4">
        <el-button type="primary" @click="searchFunds" style="width: 100%;">
          <el-icon><Search /></el-icon>搜索
        </el-button>
      </el-col>

      <el-col :xs="12" :sm="4">
        <el-button @click="resetFilters" style="width: 100%;">
          <el-icon><Refresh /></el-icon>重置
        </el-button>
      </el-col>
    </el-row>

    <p style="margin-top: 12px;">共筛选出 {{ total }} 条基金</p>

    <el-alert
        v-if="selectedFunds.length > 0"
        type="info"
        show-icon
        :title="`已选中 ${selectedFunds.length} 只基金`"
        style="margin: 10px 0;"
    />

    <!-- 基金列表表格 -->
    <el-table
        ref="fundTableRef"
        :data="funds"
        border
        style="width: 100%; margin-top: 10px;"
        @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="50" />
      <el-table-column prop="code" label="基金代码" width="120" />
      <el-table-column prop="name" label="基金名称" />
      <el-table-column prop="type" label="类型" />
      <el-table-column prop="companyName" label="基金公司" />
      <el-table-column prop="managerName" label="基金经理" />
      <el-table-column prop="latestNav" label="最新净值" />
      <el-table-column prop="latestNavDate" label="净值日期" />
      <el-table-column label="操作" width="120">
        <template #default="scope">
          <el-button
              size="small"
              type="success"
              plain
              style="display: flex; align-items: center; justify-content: center; gap: 4px;"
              @click="viewProfile(scope.row)"
          >
            查看画像
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 底部工具栏 -->
    <div class="bottom-bar">
      <span class="selected-count">已选中 {{ selectedFunds.length }} 只基金</span>
      <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
      <el-button type="success" @click="openSaveDialog">
        <el-icon><FolderAdd /></el-icon>
        保存为组合
      </el-button>
    </div>

    <!-- 保存组合弹窗 -->
    <SavePortfolioDialog
        v-model="saveDialogVisible"
        :fund-codes="selectedFunds"
        :user-id="userId"
        @saved="fetchFunds"
    />
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, Refresh, FolderAdd } from '@element-plus/icons-vue'

import { getAllTags, getFundsByPage } from '../../api/fundApi'
import SavePortfolioDialog from '@/components/funds/SavePortfolioDialog.vue'
import { useRouter } from 'vue-router'

const router = useRouter()

// refs & state
const fundTableRef = ref()
const funds = ref([])
const tags = ref([])
const selectedTags = ref([])
const keyword = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const selectedFunds = ref([])
const saveDialogVisible = ref(false)
const userId = 1

onMounted(() => {
  loadTags()
  fetchFunds()
})

// 加载标签
const loadTags = async () => {
  const res = await getAllTags()
  tags.value = res.data
}

// 加载基金分页数据
const fetchFunds = async () => {
 const res = await getFundsByPage({ // 替换为fundApi接口
    page: currentPage.value,
    size: pageSize.value,
    keyword: keyword.value,
    tagNames: selectedTags.value,
  });
  funds.value = res.data.content
  total.value = res.data.totalElements

  // 回显勾选
  nextTick(() => {
    fundTableRef.value?.clearSelection()
    funds.value.forEach(row => {
      if (selectedFunds.value.includes(row.code)) {
        fundTableRef.value.toggleRowSelection(row, true)
      }
    })
  })

}

// 跨页勾选逻辑 ✅ 核心优化
const handleSelectionChange = (selection) => {
  nextTick(() => {
    const currentPageCodes = funds.value.map(f => f.code)
    const newSelectionCodes = selection.map(f => f.code)

    // 过滤掉当前页旧数据，合并当前页最新勾选项
    const remaining = selectedFunds.value.filter(code => !currentPageCodes.includes(code))
    selectedFunds.value = [...new Set([...remaining, ...newSelectionCodes])]
  })
}


// 搜索操作
const searchFunds = () => {
  currentPage.value = 1
  fetchFunds()
}

// 重置操作
const resetFilters = () => {
  keyword.value = ''
  selectedTags.value = []
  currentPage.value = 1
  selectedFunds.value = []
  fetchFunds()
}

// 保存为组合
const openSaveDialog = () => {
  if (selectedFunds.value.length === 0) {
    ElMessage.warning('请选择要保存的基金')
    return
  }
  saveDialogVisible.value = true
}

// 查看基金画像
const viewProfile = async (row) => {
  router.push(`/fund-profile/${row.code}`)
}

// 分页逻辑
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  fetchFunds()
}
const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchFunds()
}
</script>

<style scoped>
.container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 40px;
}
.title {
  text-align: center;
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 10px;
}
.subtitle {
  text-align: center;
  font-size: 20px;
  margin-bottom: 20px;
  color: #333;
}
.filters {
  margin-bottom: 16px;
}
.bottom-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  flex-wrap: wrap;
}
.selected-count {
  font-weight: bold;
  margin-bottom: 10px;
}
</style>
